let usernameInput = document.getElementsByName("username")[0]
let passwordInput = document.getElementsByName("password")[0]
let username=usernameInput.value
let password=passwordInput.value
let code = document.getElementById("code")
let check = document.getElementById("userResult")
// 当用户名输入框失去焦点时，检查用户是否存在
usernameInput.addEventListener("blur", function () {
    let username = this.value;
    if (username.trim() !== "") {
        let xhr = new XMLHttpRequest();
        xhr.open("GET", "/user/check?username=" + encodeURIComponent(username), true);
        xhr.onreadystatechange = function () {
            if (xhr.readyState === 4) {
                if (xhr.status === 200) {
                    // 获取用户信息成功
                    let response = xhr.responseText;
                    console.log(response)
                    if (response !== "" && response != null) {
                        check.innerHTML = ""
                    } else {
                        check.innerHTML = "用户名不存在！"
                    }
                } else {
                    // 失败
                    alert('查询失败!服务器异常');
                }
            }
        }
        xhr.send();
    } else {
        check.innerHTML = ""
    }
});
code.addEventListener("click", function () {
    let xhr = new XMLHttpRequest();
    let currentUsername = document.getElementsByName("username")[0].value;
    xhr.open("GET", "/user/code?username=" + currentUsername, true)
    xhr.onreadystatechange = function () {
        if (xhr.readyState === 4) {
            if (xhr.status === 200) {
                //获取验证码成功
                let code = xhr.responseText
                alert('验证码:'+code)
            } else {
                //失败
                alert('获取失败!服务器异常')
            }
        }
    }
    xhr.send();
});
let login=document.getElementById("formSub")
login.addEventListener("submit",function (event){
    event.preventDefault()
    let xhr = new XMLHttpRequest();
    xhr.open("POST", "/common/login", true)
    xhr.setRequestHeader('Content-Type', 'application/json');
    xhr.onreadystatechange = function () {
        if (xhr.readyState === 4) {
            if (xhr.status === 200) {
                //登录成功
                window.location.href="/user/digital"
            } else {
                // 登录失败
                alert('登录失败! 请检查用户名、密码和验证码');
            }
        }
    }
    // 获取表单数据
    let username = document.getElementsByName("username")[0].value;
    let password = document.getElementsByName("password")[0].value;
    let code = document.getElementsByName("code")[0].value;
    let data={
        username:username,
        password:password,
        code:code
    }
    xhr.send(JSON.stringify(data))
});

